package com.cattsoft.user.dao.jdbcimpl;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import com.cattsoft.user.dao.IUserDAO;
import com.cattsoft.user.model.User;
import com.cattsoft.util.common.dao.jdbcimpl.ImplSupport;
import com.cattsoft.util.common.dao.jdbcimpl.JdbcDaoSupport;

public class UserDAOImpl extends JdbcDaoSupport implements IUserDAO {
	
	public void update(User user) {
		String sql = "update person set username='"+user.getUsername()+"',password='"+user.getPassword()+"' where id="+user.getId();
		getJdbcTemplate().update(sql);	
	}
		
	public void save(User user) {		 
		String id = "S_PERSON.NEXTVAL";
		String sql = "insert into person  values("+id+",'"+user.getUsername()+"','"+user.getPassword()+"')";
		getJdbcTemplate().update(sql);	
	}

	public void delete(User user) {
		String sql = "delete from person where id="+user.getId();
		getJdbcTemplate().update(sql);
	}

	public User findById(java.lang.Integer id) {
		String sql = "select * from person where id="+id;
		List lst = getJdbcTemplate().queryForList(sql);
		if(lst != null && lst.size() > 0) {
			User user = (User) ImplSupport.populate(new User(), (Map) lst.get(0));
			return user;			
		} else
			return null;	
	}

	public List findAll() {
		/*		 
		String sql = "select * from person";
		List lst = this.getJdbcTemplate().queryForList(sql);
		if(lst != null && lst.size() > 0) {
			List result = new ArrayList(lst.size());
			for(int i=0; i<lst.size(); i++) {
				User user = (User) ImplSupport.populate(new User(), (Map) lst.get(i));
				result.add(user);
			}
			return result;			
		} else
			return Empty_List;	
	   */		 
		String sql = "select * from person";
		List lst = this.getJdbcTemplate().queryForList(sql);
		if(lst != null && lst.size() > 0) {
			List result = new ArrayList(lst.size());
			Iterator it = lst.iterator();    
			while(it.hasNext()) {    
			    Map map = (Map) it.next();
			    User user = new User();
			    user.setId(Integer.valueOf(map.get("id").toString()));
			    user.setUsername(map.get("username").toString());
			    user.setPassword(map.get("password").toString());    
			    result.add(user);
			}   
			return result;			
		} else
			return Empty_List;		
	}		
}